package cn.doctor.assistant.pad.ui;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.easemob.EMCallBack;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.doctor.assistant.pad.MyApplication;
import cn.doctor.assistant.pad.R;
import cn.doctor.assistant.pad.base.BaseFragment;
import cn.doctor.assistant.pad.base.BaseNetActivity;
import cn.doctor.assistant.pad.entity.AssUser;
import cn.doctor.assistant.pad.ui.hudong.IMFragment;
import cn.doctor.assistant.pad.ui.huifang.RecallFragment;
import cn.doctor.assistant.pad.ui.tongji.StatisticsFragment;
import cn.doctor.assistant.pad.ui.zhuanzhen.TransferFragment;
import cn.doctor.assistant.pad.ui.zhuye.HomeFragment;
import cn.doctor.assistant.pad.ui.ziliao.InformationFragment;
import cn.doctor.assistant.pad.view.PopMenu;

public class MainActivity extends BaseNetActivity implements MyApplication.MessageEventListener {

    @InjectView(R.id.main_navigate_list)
    ListView mainNavigateList;

    NavigationAdapter mNavAdapter;

    @InjectView(R.id.main_doctor_icon)
    ImageView mainDoctorIcon;
    @InjectView(R.id.main_doctor_name)
    TextView mainDoctorName;

    PopMenu popMenu;
    ListView mPopList;

    // 主页左侧导航菜单项
    List<MainItem> items = new ArrayList<>(
            Arrays.asList(
                    new MainItem(R.drawable.ic_home_white_24dp, "主页", MainItem.MAIN_ITEM_TAG_HOME),
                    new MainItem(R.drawable.ic_assignment_white_24dp, "资料", MainItem.MAIN_ITEM_TAG_INFO),
                    new MainItem(R.drawable.ic_call_white_24dp, "回访", MainItem.MAIN_ITEM_TAG_RECALL),
                    new MainItem(R.drawable.ic_swap_horiz_white_24dp, "转诊", MainItem.MAIN_ITEM_TAG_TRANSFER),
                    new MainItem(R.drawable.ic_chat_white_24dp, "互动", MainItem.MAIN_ITEM_TAG_IM),
                    new MainItem(R.drawable.ic_insert_chart_white_24dp, "统计", MainItem.MAIN_ITEM_TAG_STATISTICS)
            )
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);

        initLeftNavigation();

        if (savedInstanceState == null) {
            int position = 0;
            selectItem(position, items.get(position).getTag());
        }

        // 环信登录
        loginIM();
    }

    private void initLeftNavigation() {
        // 初始化“我的医生”，医生可能有多个，需要从文件中读取上次的医生信息
        updateCurrentDoctor();

        // 导航菜单列表
        mNavAdapter = new NavigationAdapter(this, items);
        mainNavigateList.setAdapter(mNavAdapter);
        mainNavigateList.setOnItemClickListener(new MainItemClickListener());

        // 我的医生列表
        mPopList = (ListView) LayoutInflater.from(this).inflate(R.layout.layout_listview, null);
        popMenu = new PopMenu(mainDoctorIcon, mPopList);
        mPopList.setAdapter(new PopListAdapter());

        mPopList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showToast("click..." + position);
                // 切换当前医生
                MyApplication.getInstance().switchCurrentDoctor(position);
                // 更新UI
                updateCurrentDoctor();
            }
        });

        mainDoctorIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popMenu.show();
            }
        });
    }

    void updateCurrentDoctor() {
        AssUser currentDoctor = MyApplication.getInstance().mCurrDoctor;
        if (currentDoctor == null) return;
        if (!TextUtils.isEmpty(currentDoctor.getThumb())) {
            Picasso.with(this).load(currentDoctor.getThumb()).into(mainDoctorIcon);
        }
        mainDoctorName.setText(currentDoctor.getReal_name());
    }

    @Override
    public void refrush(EMNotifierEvent.Event eventType, EMMessage message) {
        if (eventType == EMNotifierEvent.Event.EventNewMessage) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mNavAdapter.setChatMessageState(true);
                }
            });
        }
    }


    private class PopListAdapter extends BaseAdapter {

        List<AssUser> doctors = new ArrayList<>();

        public PopListAdapter() {
            if (MyApplication.getInstance().mDoctors != null)
                doctors = MyApplication.getInstance().mDoctors;
        }

        @Override
        public int getCount() {
            return doctors.size();
        }

        @Override
        public Object getItem(int position) {
            return doctors.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item_home_popup, parent, false);
                holder.icon = (ImageView) convertView.findViewById(R.id.popup_doctor_icon);
                holder.name = (TextView) convertView.findViewById(R.id.popup_doctor_name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            AssUser doctor = doctors.get(position);
            if (!TextUtils.isEmpty(doctor.getThumb())) {
                Picasso.with(MainActivity.this).load(doctor.getThumb()).into(holder.icon);
            }
            holder.name.setText(doctor.getReal_name());
            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView name;
        }
    }

    private class MainItemClickListener implements
            ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position, items.get(position).getTag());
        }
    }

    private void selectItem(int position, String tag) {
        setCurrentFragmentByTag(tag);

        mainNavigateList.setItemChecked(position, true);

        // 点击后消息状态清空
        if(tag.equals(MainItem.MAIN_ITEM_TAG_IM)){
            mNavAdapter.setChatMessageState(false);
        }
    }

    private String mLastFragmentTag;

    private void setCurrentFragmentByTag(String tag) {
        FragmentManager fm = getSupportFragmentManager();

        Fragment fragment = fm.findFragmentByTag(tag);

        // 隐藏前面的Fragment
        if (mLastFragmentTag != null && !mLastFragmentTag.equals(tag)) {
            Fragment oldFragment = fm.findFragmentByTag(mLastFragmentTag);
            if (oldFragment != null) {
                fm.beginTransaction().hide(oldFragment).commit();
            }
        }

        if (fragment == null) {
            switch (tag) {
                case MainItem.MAIN_ITEM_TAG_HOME:
                    fragment = HomeFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_INFO:
                    fragment = InformationFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_RECALL:
                    fragment = RecallFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_IM:
                    fragment = IMFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_TRANSFER:
                    fragment = TransferFragment.newInstance();
                    break;
                case MainItem.MAIN_ITEM_TAG_STATISTICS:
                    fragment = StatisticsFragment.newInstance();
                    break;
            }

            fm.beginTransaction().add(R.id.content_frame, fragment, tag).commit();

        } else {
            fm.beginTransaction().show(fragment).commit();
            // 再次进入Fragment时通知一下Fragment
            if (fragment instanceof BaseFragment) {
                ((BaseFragment)fragment).onRedisplay();
            }
        }

        mLastFragmentTag = tag;
    }

    private void loginIM() {
        final String assisName = MyApplication.getInstance().mAssistUser.getLogin_name();
        final String pwd = "superDoctor"; // XXX :注意环信的密码统一是superDoctor
        EMChatManager.getInstance().login(assisName, pwd, new EMCallBack() {
            @Override
            public void onSuccess() {
                UI.showToast("登录环信成功");
                MyApplication.getInstance().setHxId(assisName);
            }

            @Override
            public void onError(int i, String s) {
                Log.e("jzsn", "环信登录失败：" + s);
            }

            @Override
            public void onProgress(int i, String s) {
            }
        });

        EMChat.getInstance().setAppInited();
        MyApplication.getInstance().addMsgEventListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMChatManager.getInstance().logout();
    }

    //======================= chat test =========================================
    /*private void showChatMessageDialog(String sender, String msg, final EMMessage emMessage) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        //如果是医生发来了消息，则助理不可回复 FIXME:测试一下
        final String myDoctorLoginName = "15136269156";
        builder.setTitle(String.format("【%s】发来消息", sender)).setMessage(msg);

        // 如果是患者发来的消息，则助理可以回复
        if (!emMessage.getFrom().equals(myDoctorLoginName)) {

            View view = UI.inflateView(R.layout.dialog_view_chat);
            builder.setView(view);
            final EditText editText = (EditText) view.findViewById(R.id.eidt_dialog_input);

            builder.setPositiveButton("回复", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) {
                    String replyText = editText.getText().toString();

                    //1. 向患者回复消息
                    replyChatMessage(emMessage, replyText);
                    //2. 转发给医生
                    sendToDoctor(emMessage, replyText);
                }
            });
        }

        builder.setNegativeButton("关闭", null).create().show();
    }

    //XXX 假设，患者向医生发送了消息，助理收到了，并回复。。。。
    private void replyChatMessage(EMMessage emMessage, String text) {

        String toChatName = emMessage.getFrom();

        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
        //如果是群聊，设置chattype,默认是单聊
        message.setChatType(EMMessage.ChatType.Chat);

        TextMessageBody txtBody = new TextMessageBody(text);
        message.addBody(txtBody);
        message.setReceipt(toChatName);

        // XXX msg_type:app,pad（助理端发的消息都加上"pad", 手机端都加上"app"）
        message.setAttribute("msg_type", "pad");

        // real_receive_id(对于患者而言，就是他本人。)
        message.setAttribute("real_receive_id", toChatName);

        // 需要向对方展示的发送者，如助理->患者，在患者端，展示的是医生。那么这个show_sender_id就是医生的id
        // 如果 医生->患者，那么助理会收到医生发来的消息，但显示的发送者，应该是自己。也就是自己的id
//        String doctorId = MyApplication.getInstance().mCurrDoctor.getLogin_name();
//        message.setAttribute("show_sender_id", doctorId); //MyApplication.getInstance().mCurrDoctor.getPhone();
        message.setAttribute("show_sender_id", "15136269156"); //XXX 测试一下

        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {

            @Override
            public void onSuccess() {
                showToast("消息已发送成功");
            }

            @Override
            public void onProgress(int arg0, String arg1) {
            }

            @Override
            public void onError(int arg0, String arg1) {
                showToast("消息发送失败");
            }
        });

    }

    // 转发给第3方（助理回复患者，同时转发给医生）
    private void sendToDoctor(EMMessage message, String text) {
        EMMessage msg = EMMessage.createSendMessage(message.getType());
        msg.setChatType(message.getChatType());
        TextMessageBody txtBody = new TextMessageBody(text);
        msg.addBody(txtBody);

        //FIXME 在做个测试，转发给医生(获取我当前的医生)
        String myDoctorId = "15136269156"; //MyApplication.getInstance().mCurrDoctor.getLogin_name();
        msg.setReceipt(myDoctorId);

        // XXX msg_type:app,pad（助理端发的消息都加上"pad", 手机端都加上"app"）
        msg.setAttribute("msg_type", "pad");
        // real_receive_id, 医生收到助理回复患者的消息，但真正的接收者，是患者，而不是医生
        // 对于患者端，这个字段可忽略。
        msg.setAttribute("real_receive_id", message.getFrom());

        // 需要向对方展示的发送者，如助理->患者，在患者端，展示的是医生。那么这个show_sender_id就是医生的id
        // 如果 医生->患者，那么助理会收到医生发来的消息，但显示的发送者，应该是自己。也就是自己的id
        msg.setAttribute("show_sender_id", myDoctorId);

        try {
            EMChatManager.getInstance().sendMessage(msg);
        } catch (EaseMobException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void refrush(EMNotifierEvent.Event eventType, final EMMessage message) {
        if (eventType == EMNotifierEvent.Event.EventNewMessage) {
            UI.showToast(message.getBody().toString());

            final String sender = message.getStringAttribute("nick", message.getFrom());

            final String msgTxt;
            if (message.getType() == EMMessage.Type.TXT) {
                TextMessageBody txtBody = (TextMessageBody) message.getBody();
                msgTxt = txtBody.getMessage();
            } else {
                msgTxt = message.getBody().toString();
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showChatMessageDialog(sender, msgTxt, message);
                }
            });
        }
    }*/
}

